home *** CD-ROM | disk | FTP | other *** search
- Path: bunyip.cc.uq.oz.au!peg!tmccoy
- From: tmccoy@peg.apc.org
- Newsgroups: comp.lang.c
- Date: 29 Jan 96 01:38 GMT+1000
- Subject: Nested Structures in C - A Question
- Message-ID: <36400002@peg>
- Sender: Notesfile to Usenet Gateway <notes@peg.apc.org>
-
- A Question on Nested Structures in C
- ------------------------------------
-
- I've recently been doing some work on the design of the C
- programming language and there seems to be an inconsistency
- in the way nested structures are defined.
-
- If I want to declare a simple structure called "outer" I
- can do the following:
-
- struct outer {
- int var1;
- int var2;
- int var3;
- };
-
- Apparently the compiler will NOT allocate any storage when
- I do this because, according to Kernighan and Ritchie (2nd
- Ed), "a structure declaration that is not followed by a
- list of variables reserves no storage; it merely describes
- a template or the shape of a structure" (Page 128).
-
- This is all well and good. And when I want to define a new
- structure *within* my old one, I should be able to do:
-
- struct outer {
- int var1;
- int var2;
- int var3;
- struct inner {
- int nested1;
- int nested2;
- };
- };
-
- and I should be able to define an instance of my structure
- by doing:
-
- struct outer instance;
-
- and refer to the first member of my inner structure by doing:
-
- instance.inner.nested1
-
- Yet, C won't let me do this!! It insists that I define my
- nested structure as follows:
-
- struct outer {
- int var1;
- int var2;
- int var3;
- struct inner {
- int nested1;
- int nested2;
- } DUMMY;
- };
-
- and after doing
-
- struct outer instance;
-
- I must refer to the first member of my inner structure by
- doing:
-
- instance.DUMMY.nested1
-
- i.e. I must access the inner members via a variable (called
- "DUMMY") instead of being able to use my structure tag
- (i.e. "inner"). In fact, the *only way* I can access the
- inner members is by defining the DUMMY variable within the
- structure template of "outer".
-
- I am just wondering whether anybody else has found this to
- be strange and if anybody knows why the nested structure
- feature has been designed in this way.
-
- I'm also curious about how compilers would implement this
- feature.
-
- With a nested structure, as with a simple structure, I
- *should* be able to define a pure structure template in
- which no storage is allocated. Yet, in the definition I am
- forced to use above, strictly speaking the compiler should
- allocate storage for "DUMMY" even though the enclosing
- structure (i.e. "outer") is only a template.
-
- I find this very inconsistent and it is a feature that bugs
- me about an otherwise elegant language.
-
- Does it bother anybody else? Or am I just looking at it
- all the wrong way?
-
- Any comments, via conference or e-mail, would be
- appreciated.
-
- Cheers from Canberra, Australia,
-
- Tom
-